package com.downbox.scheduler;

import com.downbox.domain.Contribution;
import com.downbox.repository.ContributionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 投稿定时任务
 */
@Component
public class ContributionScheduler {

    @Autowired
    private ContributionRepository contributionRepository;

    /**
     * 每小时执行一次，处理超过24小时未审核的投稿
     */
    @Scheduled(cron = "0 0 * * * ?")
    @Transactional
    public void processExpiredContributions() {
        LocalDateTime threshold = LocalDateTime.now().minusHours(24);
        List<Contribution> expiredContributions = contributionRepository.findByStatusAndCreatedAtBefore(
                Contribution.ContributionStatus.PENDING,
                threshold
        );

        for (Contribution contribution : expiredContributions) {
            contribution.setStatus(Contribution.ContributionStatus.REJECTED);
            contribution.setReviewedAt(LocalDateTime.now());
            contributionRepository.save(contribution);
        }
    }
}